package org.jash.imdemo;

import android.os.Bundle;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.List;

public class ChatActivity extends AppCompatActivity {
    private MaterialToolbar toolbar;
    private String toName;
    private RecyclerView recycler;
    private MessageAdapter adapter;

    private EditText content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        toolbar = findViewById(R.id.toolbar);
        toName = getIntent().getStringExtra("toName");
        toolbar.setTitle("与" + toName + "聊天");
        toolbar.setNavigationOnClickListener(v -> finish());
        recycler = findViewById(R.id.recycler);
        adapter = new MessageAdapter();
        recycler.setAdapter(adapter);
        new Thread(() -> {

            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(toName);
            if (conversation != null) {
                List<EMMessage> list = conversation.getAllMessages();
                runOnUiThread(() -> adapter.addAll(list));
            }
        }).start();
        content = findViewById(R.id.content);
        findViewById(R.id.send).setOnClickListener(v -> {
            EMMessage message = EMMessage.createTxtSendMessage(content.getText().toString(), toName);
            EMClient.getInstance().chatManager().sendMessage(message);
            adapter.addAll(List.of(message));
        });
    }
}